const fp = require('loadsh/fp');
/**
 * 数据:
 *      horsepower:马力; dollar_value:价格; in_stock:库存
 */
const car = [
    { name: 'Ferrari FF', horsepower: 660, dollar_value: 700000, in_stock: true },
    { name: 'Spyker C12 Zagato', horsepower: 650, dollar_value: 648000, in_stock: true },
    { name: 'Jaguar xkr-s', horsepower: 550, dollar_value: 132000, in_stock: true },
    { name: 'Audi R8', horsepower: 525, dollar_value: 114200, in_stock: true },
    { name: 'Aston Martin One-77', horsepower: 660, dollar_value: 1850000, in_stock: true },
    { name: 'Pagani', horsepower: 700, dollar_value: 130000, in_stock: true },
]

/**
 * 使用fp.flowRight() 重新实现isLastInStrock
    let isLastInStrock = function (cars) {
        // 获取最后一条数据
        let last_car = fp.last(cars)
        // 获取最后一条数据的in_stock属性
        return fp.prop('in_stock', last_car)
    }
 */
let last_car = arr => fp.last(arr)
let getInStock = obj => fp.prop('in_stock', obj)
let isLastInStrock = fp.flowRight(getInStock, last_car)
console.log(isLastInStrock(car));

/**
 * 使用fp.flowRight()\fp.prop()\fp.first()获取第一个车的name值
 */
let first_car = arr => fp.first(arr);
let getName = obj => fp.prop('name', obj);
let isFirstCarName = fp.flowRight(getName, first_car)
console.log(isFirstCarName(car));

/**
 *  使用帮助函数 _average重构averageDollarValue,使用函数组合实现
 */
let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length;
}

let dollar_values = (cars) => fp.map((car) => car.dollar_value, cars);
let averageDollarValue = fp.flowRight(_average, dollar_values);
console.log(averageDollarValue(car));

/**
 * 使用fp.flowRight()写一个sanitizeNames()
 *  返回一个下划线链接的小写字符串
 */
let _underscore = fp.replace(/\W+/g, '_')
let sanitizeNames = fp.flowRight(fp.toLower, fp.map(_underscore), fp.map(fp.prop('name')))
console.log(sanitizeNames(car));